<!--
 * @Author: swc shanwenchao12138@163.com
 * @Date: 2024-10-15 18:10:34
 * @LastEditors: swc
 * @LastEditTime: 2025-02-18 14:37:17
 * @FilePath: \stdsys\src\components\custom\homePage\homeCpt\o-message-list\index.vue
 * @Description: 
 * @Version: 2.0
 * @Autor: swc
-->
<template>
  <i-col
    :lg="12"
    :sm="24"
    :style="{
      flex: '0 0 calc(' + 25 * ffieldwidth + '%' + ' - ' + 10 + 'px)',
      height: fheight ? fheight + 'px' : '100%'
    }"
  >
    <div class="message-list">
      <header class="clear">
        <div class="header-left">
          <!-- {{ `${$srv.getI18nBySrv('大分类')}-${$srv.getI18nBySrv('小分类')}` }} -->
          {{ $srv.getI18nBySrv('消息') }}
        </div>
        <div class="header-center">
          <Cascader
            v-if="isIndependent"
            v-model="msgFilter"
            :data="msgOptions"
            filterable
            clearable
            trigger="click"
            :change-on-select="true"
            @on-change="msgFilterChange"
          />
        </div>
        <div class="header-right">
          <!-- <Button
            v-show="true"
            class="button icon"
            :class="iconActive === 'asc' ? 'iconActive' : ''"
            icon="md-arrow-dropup"
            size="small"
            @click="msgSort('asc')"
          ></Button>
          <Button
            v-show="true"
            class="button icon"
            :class="iconActive === 'desc' ? 'iconActive' : ''"
            icon="md-arrow-dropdown"
            size="small"
            @click="msgSort('desc')"
          ></Button>
          <Button
            class="button"
            icon="ios-funnel-outline"
            size="small"
            @click="msgSort('desc')"
          ></Button> -->
          <Button
            class="button"
            v-show="true"
            icon="md-refresh"
            size="small"
            @click="refresh"
          ></Button>
          <!-- <span v-show="true">
            {{ $srv.getI18nByPath('others.more') }}
            <i class="ivu-icon ivu-icon-ios-arrow-forward"></i>
          </span> -->
        </div>
      </header>
      <main class="message-list-body">
        <Table
          size="small"
          border
          stripe
          highlight-row
          :columns="columns"
          :data="msgList"
          :row-class-name="rowClassName"
          :show-header="true"
          :no-data-text="$srv.getI18nByPath('others.nodata')"
          @on-row-dblclick="handleDbclick"
          ref="mTable"
        >
          <template #action="{ row, index }">
            <span
              :class="[
                'wy-icon',
                'wy-huishouzhan1',
                'delete-icon',
                row.status ? '' : 'cursor-not-allowed'
              ]"
              @click="deleteMsg(row, index)"
            ></span>
          </template>
        </Table>
      </main>
      <footer>
        <Page
          :total="pagerConfig.total"
          :prev-text="$srv.getI18nByPath('vxe.pager.prevPage')"
          :next-text="$srv.getI18nByPath('vxe.pager.nextPage')"
          show-sizer
          show-elevator
          transfer
          show-total
          :model-value="pagerConfig.currentPage"
          :page-size-opts="[10, 30, 100, 200, 500, 1000]"
          :page-size="pagerConfig.pageSize"
          @on-change="pageChange"
          @on-page-size-change="pageSizeChange"
        />
      </footer>
    </div>
  </i-col>
</template>

<script lang="ts">
import {
  Tsrv,
  T_srv,
  ifs,
  ts,
  tvs,
  vue,
  I_cmd,
  T_cmd,
  getMsgOptions,
  getColumns
} from './config';
import { N_oMessageList } from './type';

interface I_config {
  filters?: Map<string, Set<string | number | null>>;
  visibility?: Map<string, Set<string | number | null>>;
}

@T_srv.comp
export default class oMessageList extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @T_srv.prop({})
  ffieldwidth: number;

  @T_srv.prop({})
  fheight: number;

  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  config: any;

  $refs!: {
    mTable: any;
  };

  /* 组件名 */
  private name: string = 'oMessageList';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  private msgList: any[] = [];

  private msgData: any[] = [];

  private msgFilter: any[] = [];

  private filters: Map<string, Set<string | number | null>> = new Map();

  private visibility: Map<string, Set<string | number | null>> = new Map();

  private msgOptions: N_oMessageList.I_filterOption[] = getMsgOptions();

  private iconActive: string = 'asc';

  private columns: any[] = getColumns();

  // 是否自治
  private isIndependent: boolean = true;

  private pagerConfig: any = {
    pageSize: 10,
    currentPage: 1,
    total: 0,
    pageTotal: null
  };

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);

    this.GT_command.getTableData();

    /* 最终应用组件向外抛出引用实例,以供应用间调用 */
    // Tsrv.compBox.addCompMergeName(
    //   Tsrv.compBox.getDefGUID(), // 全局compBox
    //   '????',
    //   this,
    //   '???'
    // );
  }

  private init() {
    this.isIndependent = !this.config;
    this.initFilters();
    this.initConfig();
  }

  public initFilters() {
    this.filters.clear();
    this.filters.set(
      Tsrv.globalVar.fieldName.msgReceiver,
      new Set([Tsrv.getStore().state.User.userNo])
    );
    this.filters.set(Tsrv.globalVar.fieldName.msgStatus, new Set([0, 1]));
  }

  private initConfig() {
    // 如果有配置项（即：）
    if (!Tsrv.noValue(this.config)) {
      // 初始化过滤
      const { filter, visibility } = this.config;
      if (filter instanceof Map && filter.size > 0) {
        for (const key of filter.keys()) {
          // 特殊情况（）：消息状态
          if (key === Tsrv.globalVar.fieldName.msgStatus) {
            this.filters.set(key, filter.get(key));
            continue;
          }
          // 其他
          if (this.filters.has(key)) {
            // this.filters.get(key)?.add(filter.get(key));
            this.filters.set(
              key,
              new Set([...this.filters.get(key), ...filter.get(key)])
            );
          } else {
            this.filters.set(key, filter.get(key));
          }
        }
      }
      // if (visibility instanceof Map && visibility.size > 0) {
      //   for (let key of visibility.keys()) {
      //     if (visibility.get(key)) {
      //       this.columns.forEach((item: any) => {
      //         if
      //     }
      //   }
    }
  }

  private handleDbclick(row: any, index: number) {
    if (Tsrv.noValues(row?.type, row?.category, row?.id)) {
      this.$msg(Tsrv.getI18nByValue('此消息数据不完整'));
      return;
    }
    const { type, category } = Tsrv.wsCommunicate.getMsgTypeAndCategory(
      row.type,
      row.category
    );
    const [name, config] = this.handleMessageConfig(row);

    if (Tsrv.noValue(name) || Tsrv.noValue(config)) {
      this.$msg(Tsrv.getI18nByValue('无此消息类型组件'));
    } else {
      if (!this.isIndependent) {
        this.$emit('on-row-dbclick', row);
      }
      const modalConfig: any = {
        modalTitle: `${Tsrv.getI18nBySrv(type)}：${Tsrv.getI18nBySrv(
          row.title
        )}`,
        modalSize: [600, 500],
        msgConfig: config
      };
      // if (name === 'o-approval-info') {
      //   modalConfig['onlyFlow'] = true;
      // }
      if (row.status === 0) {
        // 2、 打开消息详情
        Tsrv.wsCommunicate
          .modifyMsgRead(row.id, row.type, row.category)
          .then(res => {
            if (res) {
              this.GT_command.getTableData();
              Tsrv.utils.createModal(name, modalConfig).then(resp => {});
            }
          });
      } else {
        Tsrv.utils.createModal(name, modalConfig).then(resp => {});
      }
    }
  }

  // 筛选
  private msgFilterChange(filter: Array<any>) {
    // 根据消息类型筛选
    if (this.msgFilter.length === 0 || this.msgFilter[0] !== filter[0]) {
      this.filters.set(Tsrv.globalVar.fieldName.msgType, new Set([filter[0]]));
      if (filter[0] === undefined) {
        this.filters.delete(Tsrv.globalVar.fieldName.msgType);
      }
      this.GT_command.getTableData();
    }
    // 根据消息小分类修改指定category消息的底色
    if (
      this.msgFilter.length > 0 &&
      filter.length > 1 &&
      this.msgFilter[0] === filter[0]
    ) {
      const category = filter[1];
      // this.visibility.set(category, true);
      // 改变制定category消息的底色
    }
  }

  // 排序
  private msgSort(sort: string) {}

  // 刷新
  public refresh() {
    this.GT_command.getTableData();
  }

  // 页数改变
  private pageChange(page: number) {
    this.pagerConfig.currentPage = page;
    if (
      !Tsrv.noValue(this.pagerConfig.pageTotal) &&
      this.pagerConfig.pageTotal >= page
    ) {
      this.GT_command.getTableData();
    }
  }

  // 页size改变
  private pageSizeChange(pageSize) {
    this.pagerConfig.pageSize = pageSize;
    if (this.pagerConfig.currentPage === 1) {
      this.GT_command.getTableData();
    }
  }

  // 行样式控制
  private rowClassName(row: any, index: number) {
    const rowClass = [];
    if (row?.status === 1) {
      rowClass.push('msg-read');
    }
    return rowClass;
  }

  // 消息删除
  private deleteMsg(row: any, index: number) {
    this.GT_command.deleteMsg(row, index);
  }

  // 消息已读
  private readMsg(row: any, index: number) {}

  public getFilter() {
    const filter: ts.T_filter = new ts.T_filter();
    filter.filter = filter.parseSelectFilter(this.filters);
    return filter;
  }

  /**
   * @description: 消息详情页面（弹窗）config配置
   * @param {*} row
   * @return {*}
   * @author: swc
   * @Date: 2024-12-09 13:25:58
   * @LastEditors: swc
   * @LastEditTime: Do not edit
   */
  private handleMessageConfig(row: any): Array<any> {
    switch (row.type) {
      // case tvs.V_msgType.ALARM:
      //   break;
      case tvs.V_msgType.BROADCAST:
        return this.handleBroadcastCfg(row);
      // case tvs.V_msgType.EARLY_WARNING:
      //   break;
      case tvs.V_msgType.NOTICE:
        return this.handleNoticeCfg(row);
      case tvs.V_msgType.TO_DO_LIST:
        return this.handleTodoCfg(row);
      default:
        this.$msg(Tsrv.getI18nByValue('暂无此消息类型UI'));
        break;
    }
    return ['', null];
  }

  private handleNoticeCfg(row: any): Array<any> {
    let name = '';
    let config;
    const content = row.content;
    const category = content?.category;
    if (!Tsrv.noValue(content)) {
      name = 'o-msg-notice';
      config = new ts.T_msgNotice(
        content.title,
        content.content,
        content.category
      );
    }
    return [name, config];
  }

  private handleTodoCfg(row: any): Array<any> {
    let name = '';
    let config: ts.T_msgToDoList;
    const content = row.content;
    const category = content?.category;
    if (category === tvs.V_todoListCategory.APPROVAL) {
      name = 'o-approval-info';
    }
    if (!Tsrv.noValue(content)) {
      config = new ts.T_msgToDoList(
        content.title,
        content.content,
        content.category,
        content.liaisonID
      );
    }
    return [name, config];
  }

  private handleBroadcastCfg(row: any): Array<any> {
    let name = '';
    let config;
    const content = row.content;
    const category = content?.category;
    if (!Tsrv.noValue(content)) {
      name = 'o-msg-broadcast';
      config = new ts.T_msgBroadcast(
        content.title,
        content.content,
        content.category
      );
    }
    return [name, config];
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 最终应用组件销毁 */
    /* this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName,'funName'); */

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
    /* 如果是动态组件可能会关闭全局compBox */
    // this.GT_compBox = null
  }
}
</script>
<style lang="scss" scoped>
.ivu-col {
  height: 400px;
  margin: 5px;
  overflow: hidden;
}
.message-list {
  // width: 100%;
  height: 100%;
  padding: 0 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;
  background-color: #fff;
  header {
    flex: 0 0 40px;
    height: 40px;
    width: 100%;
    border-bottom: 1px solid #e8eaec;
    font-size: 15px;
    // height: 36px;
    line-height: 40px;
    // position: relative;
    padding-left: 12px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    flex-wrap: nowrap;
    overflow: hidden;

    &::before {
      content: '';
      display: block;
      background-color: var(--main-container-bg-color);
      width: 4px;
      height: 60%;
      position: absolute;
      top: 20%;
      left: 0;
    }
    // .header-left {
    //   // float: left;
    // }
    .header-center {
      flex: 1;
      display: grid;
      place-items: center;
      padding: 0 10px;
    }
    .header-right {
      font-size: 13px;
      span {
        cursor: pointer;
        i {
          font-size: 16px;
          color: inherit;
        }
      }
      a {
        font-size: 12px;
        background-color: #ed4014;
        color: #fff;
        display: inline-block;
        padding: 3px 8px;
        margin-right: 10px;
        line-height: 1.2;
        border-radius: 4px;
      }
      .button {
        margin-right: 10px;
      }
      .icon {
        color: rgb(200, 200, 200);
      }
      .iconActive {
        color: rgb(81, 90, 110);
      }
    }
  }
  main {
    flex: 1;
    height: 100%;
    width: 100%;
    overflow-y: auto;
    margin-top: 5px;
    border-bottom: 1px solid var(--navSub-hover-bg-color);
    .no-info img {
      width: 265px;
      display: block;
      margin: 20px auto 0 auto;
    }

    ::v-deep .ivu-table .msg-read td {
      background-color: #f8f8f8;
      color: #c0c4cc;
    }
    ::v-deep .ivu-table {
      .delete-icon {
        color: red;
        cursor: pointer;
        &:hover {
          color: #2d8eff;
        }
      }
      .cursor-not-allowed {
        cursor: not-allowed;
        color: #c0c4cc;
        // &:hover {
        //   color: #c0c4cc;
        // }
      }
    }
  }
  footer {
    flex: 0 0 40px;
    height: 40px;
    width: 100%;
    margin-top: 5px;
  }
}
</style>
